var constant = require('../common/constant')

var tools = {
    requestWithAuth: function (params) {
        var that = this
        var auth = require('../auth/login')
        auth.checkLogin({
            success: function (dt) {
                params.url = constant.system.apiHost + params.url
                if ('undefined' == typeof params.data) {
                    params.data = {};
                }
                params.data['open_id'] = dt.token
                params.success = function (res) {
                    that.formatResponse(res, params.feedback) 
                }
                wx.request(params)
            }
        });
    },
    normalRequest: function (params) {
        var that = this
        params.url = constant.system.apiHost + params.url,
        params.success = function (res) {
            that.formatResponse(res, params.feedback) 
        }
        wx.request(params)
    },
    formatResponse: function (response, feedback) {
        if ('403' == response.statusCode) {
            //var auth = require('../auth/login')
            //auth.login({
            //    success: function () {
            //        feedback.success(response.data)
            //    }
            //});
        } else if ('500' == response.statusCode) {
            console.log('server is over~')
            return false
        }
        //TODO::格式化响应数据
        var responseData = {}
        if ('object' == typeof response.data) {
            responseData = response.data;
        } else if ('string' == typeof response.data) {
            responseData = JSON.parse(response.data) 
        } else {
            feedback.fail(response.data);
            return false;
        }
        feedback.success(responseData)
        return true;
    },
    getCurrentPageRoute: function () {
        var pages = getCurrentPages()
        var currentPage = pages[pages.length - 1]
        return currentPage.route
    }
}

module.exports = tools